import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';

export default class SurchargeStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['sortWeight;desc'],
      size: 10,
    },
  };
  total = 0;
  loading = false;
  charges = [];

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  * create(data) {
    yield api.dictCreate(data);
    this.get(data.dictId);
  }

  * update(data) {
    yield api.dictUpdate('taurusSurcharges', data);
    this.get(data.dictId);
  }

  * get() {
    const res = yield api.getDict({ pg: { sort: ['sortWeight;desc'], page: 0, size: 999 } });
    this.charges = res;
  }

  * dictDelete(name) {
    yield api.dictDelete('taurusSurcharges', name);
  }

  idx(i, p, s) {
    return p * s + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }
}
